/*
 * Copyright ShangHai ECLUB Information Technology Co.,Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.eclub.emotion.rootstone.server.core.communication.http;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpServerCodec;

import com.bj58.spat.gaea.server.contract.context.IProxyFactory;
import com.bj58.spat.gaea.server.deploy.bytecode.CreateManager;
import com.bj58.spat.gaea.server.deploy.hotdeploy.ProxyFactoryLoader;
import com.eclub.emotion.rootstone.server.context.Global;
import com.eclub.emotion.rootstone.server.context.ServiceConfig;


/**
 *A easier server side HTTP implementation , the httpServer is NETTY based. 
 *
 * @author   jun.yang, Wincor Nixdorf International GmbH
 */
public class HttpServer {
	private Logger logger = Logger.getLogger(HttpServer.class);
	private static final ServerBootstrap bootstrap = new ServerBootstrap();
	static final ChannelGroup channelGroup = new DefaultChannelGroup("rootstone-HttpServer");
	public  static String errorPageHTML = null;
	
	public void start() throws Exception {
		logger.info("Startup Rootstone HttpServer..");
		
		logger.info("Starting initialize Server..");
		initHttpServer();
		
	}
	
	/**
	 * initialize HTTP Server
	 * @throws Exception
	 */
	private void initHttpServer() throws Exception {
		final boolean tcpNoDelay = true;
		logger.info("-----------------http server config-----------------");
		logger.info("-- listening ip: " + Global.getSingleton().getServiceConfig().getString("rs.server.http.listenIP"));
        logger.info("-- port: " + Global.getSingleton().getServiceConfig().getInt("rs.server.http.listenPort"));
        logger.info("-- tcpNoDelay: " + tcpNoDelay);
        logger.info("-- receiveBufferSize: " + Global.getSingleton().getServiceConfig().getInt("rs.server.http.receiveBufferSize"));
        logger.info("-- sendBufferSize: " + Global.getSingleton().getServiceConfig().getInt("rs.server.http.sendBufferSize"));
        logger.info("-- frameMaxLength: " + Global.getSingleton().getServiceConfig().getInt("rs.server.http.frameMaxLength"));
        logger.info("-- worker thread count: " + Global.getSingleton().getServiceConfig().getInt("rs.server.http.workerCount"));
        logger.info("-----------------------------------------------------");		
		logger.info(Global.getSingleton().getServiceConfig().getString("rs.service.name") + " HttpServer starting...");

        bootstrap.setFactory(new NioServerSocketChannelFactory(
			                        	Executors.newCachedThreadPool(),
			                        	Executors.newCachedThreadPool(),
			                        	Global.getSingleton().getServiceConfig().getInt("rs.server.http.workerCount")
			                        )
        					);
        
        final NettyRequestTransport handler = new NettyRequestTransport();
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				pipeline.addLast("httpServerCodec", new HttpServerCodec());
				pipeline.addLast("httpChunkAggregator", new HttpChunkAggregator(1024 * 1024 * 8));
				pipeline.addLast("httpContentCompressor", new HttpContentCompressor());
				pipeline.addLast("httpHandler", handler);
				return pipeline;
			}
		});
        bootstrap.setOption("child.tcpNoDelay", tcpNoDelay);
        bootstrap.setOption("child.receiveBufferSize", 
        		Global.getSingleton().getServiceConfig().getInt("rs.server.http.receiveBufferSize"));
        bootstrap.setOption("child.sendBufferSize", 
        		Global.getSingleton().getServiceConfig().getInt("rs.server.http.sendBufferSize"));

        try {
        	InetSocketAddress socketAddress = null;
        	socketAddress = new InetSocketAddress(Global.getSingleton().getServiceConfig().getString("rs.server.http.listenIP"),
        			Global.getSingleton().getServiceConfig().getInt("rs.server.http.listenPort"));
            Channel channel = bootstrap.bind(socketAddress);
            channelGroup.add(channel);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	public static void main(String[] args) throws Exception{
		main();
		HttpServer server = new HttpServer();
		server.start();
	}
	
	private static void main() throws Exception{
		String rootPath = "D:/code/Gaea/gaea/";
		String serviceName = "demo";
		Map<String, String> argsMap = new HashMap<String, String>();
		Global.getSingleton().setRootPath(rootPath);
		
		
		String serviceFolderPath = rootPath + "service/deploy/" + serviceName;
		String gaeaConfigDefaultPath = rootPath + "conf/gaea_config.xml";
		String gaeaConfigPath = serviceFolderPath + "/gaea_config.xml";
		
		
		
		// load service config
		ServiceConfig sc = loadServiceConfig(gaeaConfigDefaultPath, gaeaConfigPath);
		sc.set("rs.service.name", serviceName);
		Global.getSingleton().setServiceConfig(sc);
		
		CreateManager cm = new CreateManager();
		return cm.careteProxy(Global.getSingleton().getRootPath() 
								  + "service/deploy/" 
								  + Global.getSingleton().getServiceConfig().getString("gaea.service.name"), 
							  classLoader);
		IProxyFactory proxyFactory = ProxyFactoryLoader.loadProxyFactory(classLoader);
		Global.getSingleton().setProxyFactory(proxyFactory);

	}
	
	private static ServiceConfig loadServiceConfig(String... cps) throws Exception {
		ServiceConfig sc = ServiceConfig.getServiceConfig(cps);
		
		return sc;
	}
	
}
